import { CoolController, BaseController } from '@cool-midway/core';
import { ErpOrdersEntity } from '../../entity/erpOrders';
import { Body, Inject, Post, Provide } from '@midwayjs/decorator';
import { EXCEL_MAP } from '../../contanst/erpOrders';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { ErpOrdersService } from '../../service/erpOrders';
import moment = require('moment');

@Provide()
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: ErpOrdersEntity,
  listQueryOp: {
    fieldEq: ['erp_data_date'],
    keyWordLikeFields: ['erp_order_number', 'order_number', 'store_name'],
  },
  pageQueryOp: {
    fieldEq: ['erp_data_date'],
    keyWordLikeFields: ['erp_order_number', 'order_number', 'store_name'],
  },
})
export class APIController extends BaseController {
  @InjectEntityModel(ErpOrdersEntity)
  erpOrdersEntity: Repository<ErpOrdersEntity>;

  @Inject()
  erpOrdersService: ErpOrdersService;

  @Post('/import')
  async import(
    @Body('list') data,
    @Body('erp_data_date') erp_data_date,
    @Body('store_name') store_name
  ) {
    const records: any[] = [];
    data.forEach(item => {
      const record: any = {};
      Object.keys(EXCEL_MAP).forEach(key => {
        if (EXCEL_MAP[key]) {
          record[EXCEL_MAP[key]] = item[key]?.replace?.(/\t/g, '') || item[key];
        }
        if (item[key] === "'手工建单" || item[key] === '手工建单') {
          return;
        }
        record.erp_data_date = moment(erp_data_date).format('YYYY-MM-DD');
        record.store_name = store_name;
        if (typeof record.cost === 'number') {
          records.push(record);
        }
      });
    });

    this.erpOrdersService.upsert(records);
    return this.ok();
  }
}
